import { constantRouterMap, appRouter } from '@/router/index'

// console.log(2,Date.now());
// console.log('router1', constantRouterMap);

// setTimeout(() => {
//     console.log('router2', constantRouterMap);
// }, 2000);

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param route
 * @param roles
 */
function hasPermission(roles, route) {
    if( route.access ) {
        return roles.some(role => route.access === role );
    } else {
        return true;
    }
}

/**
 *  返回符合角色的路由表
 *  @param asyncRouterMap
 *  @param roles
 */ 
function filterAsyncRouter(asyncRouterMap, roles) {
    let accessedRouters = asyncRouterMap.filter(route => {
        if(hasPermission(roles, route)) {
            if(route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, roles);
            }
            return true;
        }
        return false;
    })
    return accessedRouters;
}


const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: []
    },

    mutations: {
        Set_routers(state, routers) {
            state.addRouters = routers;
            state.routers = constantRouterMap.concat(routers);
        }
    },
    actions: {
        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
                const roles = data;
                let accessedRouters = filterAsyncRouter(appRouter, roles);
                commit('Set_routers', accessedRouters);
                resolve();
            })
        }
    }
}

export default permission